<template>
  <el-dialog
    v-model="visible"
    title="添加数据源"
    width="600px"
    :before-close="handleClose">
    
    <div class="data-source-dialog">
      <!-- 数据源类型选择 -->
      <div v-if="step === 1" class="step-content">
        <h4>选择数据源类型</h4>
        <div class="source-types">
          <div 
            v-for="template in dataSourceTemplates" 
            :key="template.id"
            class="source-type-card"
            :class="{ 'selected': selectedTemplate?.id === template.id }"
            @click="selectTemplate(template)">
            
            <div class="card-icon">
              <el-icon size="32">
                <component :is="getIcon(template.icon)" />
              </el-icon>
            </div>
            <div class="card-content">
              <h5>{{ template.name }}</h5>
              <p>{{ template.description }}</p>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 数据源配置 -->
      <div v-if="step === 2" class="step-content">
        <h4>配置数据源</h4>
        <el-form 
          ref="formRef" 
          :model="formData" 
          :rules="formRules" 
          label-width="120px"
          size="default">
          
          <el-form-item label="数据源名称" prop="name">
            <el-input v-model="formData.name" placeholder="请输入数据源名称" />
          </el-form-item>
          
          <el-form-item label="描述" prop="description">
            <el-input 
              v-model="formData.description" 
              type="textarea" 
              :rows="3"
              placeholder="请输入数据源描述" />
          </el-form-item>
          
          <!-- 动态字段 -->
          <el-form-item 
            v-for="field in selectedTemplate?.fields || []" 
            :key="field.name"
            :label="field.label"
            :prop="field.name">
            
            <!-- 文本输入 -->
            <el-input 
              v-if="field.type === 'text'"
              v-model="formData[field.name]"
              :placeholder="`请输入${field.label}`" />
            
            <!-- 数字输入 -->
            <el-input-number 
              v-else-if="field.type === 'number'"
              v-model="formData[field.name]"
              :min="0"
              style="width: 100%" />
            
            <!-- 密码输入 -->
            <el-input 
              v-else-if="field.type === 'password'"
              v-model="formData[field.name]"
              type="password"
              show-password
              :placeholder="`请输入${field.label}`" />
            
            <!-- 选择框 -->
            <el-select 
              v-else-if="field.type === 'select'"
              v-model="formData[field.name]"
              style="width: 100%">
              <el-option 
                v-for="option in field.options" 
                :key="option"
                :label="option"
                :value="option" />
            </el-select>
            
            <!-- 文件上传 -->
            <el-upload
              v-else-if="field.type === 'file'"
              class="upload-demo"
              drag
              :auto-upload="false"
              :on-change="handleFileChange"
              :limit="1">
              <el-icon class="el-icon--upload"><Upload /></el-icon>
              <div class="el-upload__text">
                将文件拖到此处，或<em>点击上传</em>
              </div>
              <template #tip>
                <div class="el-upload__tip">
                  支持 .xlsx, .xls, .csv 格式文件
                </div>
              </template>
            </el-upload>
            
            <!-- 多行文本 -->
            <el-input 
              v-else-if="field.type === 'textarea'"
              v-model="formData[field.name]"
              type="textarea"
              :rows="3"
              :placeholder="`请输入${field.label}`" />
            
            <!-- 布尔值 -->
            <el-switch 
              v-else-if="field.type === 'boolean'"
              v-model="formData[field.name]" />
          </el-form-item>
        </el-form>
      </div>
      
      <!-- 数据预览 -->
      <div v-if="step === 3" class="step-content">
        <h4>数据预览</h4>
        <div class="preview-section">
          <div class="preview-info">
            <el-alert
              title="数据连接成功"
              type="success"
              :closable="false"
              show-icon>
              <template #default>
                <p>检测到 {{ previewData.tables?.length || 0 }} 个表，共 {{ totalRows }} 行数据</p>
              </template>
            </el-alert>
          </div>
          
          <div class="tables-preview">
            <el-tabs v-model="activeTable" type="border-card">
              <el-tab-pane 
                v-for="table in previewData.tables" 
                :key="table.name"
                :label="`${table.name} (${table.rows?.length || 0}行)`"
                :name="table.name">
                
                <div class="table-preview">
                  <el-table 
                    :data="table.rows?.slice(0, 10) || []" 
                    style="width: 100%"
                    size="small"
                    max-height="300">
                    <el-table-column 
                      v-for="column in table.columns" 
                      :key="column.name"
                      :prop="column.name"
                      :label="column.name"
                      :width="120"
                      show-overflow-tooltip />
                  </el-table>
                  
                  <div v-if="(table.rows?.length || 0) > 10" class="preview-tip">
                    <el-text type="info">仅显示前10行数据，实际共 {{ table.rows?.length }} 行</el-text>
                  </div>
                </div>
              </el-tab-pane>
            </el-tabs>
          </div>
        </div>
      </div>
    </div>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button v-if="step > 1" @click="prevStep">上一步</el-button>
        <el-button 
          v-if="step < 3" 
          type="primary" 
          :disabled="!canNext"
          @click="nextStep">
          下一步
        </el-button>
        <el-button 
          v-if="step === 3" 
          type="primary" 
          :loading="loading"
          @click="confirmAdd">
          确认添加
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { useDataModelStore } from '../../stores/dataModelStore'
import { ElMessage } from 'element-plus'
import { 
  Document, 
  Grid, 
  Connection, 
  Upload 
} from '@element-plus/icons-vue'

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['update:modelValue', 'data-source-added'])

// 数据模型store
const dataModelStore = useDataModelStore()

// 响应式数据
const visible = ref(false)
const step = ref(1)
const selectedTemplate = ref(null)
const formRef = ref(null)
const loading = ref(false)
const activeTable = ref('')

const formData = ref({
  name: '',
  description: ''
})

const previewData = ref({
  tables: []
})

// 计算属性
const dataSourceTemplates = computed(() => dataModelStore.dataSourceTemplates)

const totalRows = computed(() => {
  return previewData.value.tables?.reduce((total, table) => total + (table.rows?.length || 0), 0) || 0
})

const canNext = computed(() => {
  if (step.value === 1) {
    return selectedTemplate.value !== null
  }
  if (step.value === 2) {
    return formData.value.name.trim() !== ''
  }
  return true
})

const formRules = computed(() => {
  const rules = {
    name: [
      { required: true, message: '请输入数据源名称', trigger: 'blur' }
    ]
  }
  
  // 动态添加字段验证规则
  if (selectedTemplate.value?.fields) {
    selectedTemplate.value.fields.forEach(field => {
      if (field.required) {
        rules[field.name] = [
          { required: true, message: `请输入${field.label}`, trigger: 'blur' }
        ]
      }
    })
  }
  
  return rules
})

// 监听器
watch(() => props.modelValue, (val) => {
  visible.value = val
  if (val) {
    resetDialog()
  }
})

watch(visible, (val) => {
  emit('update:modelValue', val)
})

// 方法
const resetDialog = () => {
  step.value = 1
  selectedTemplate.value = null
  formData.value = {
    name: '',
    description: ''
  }
  previewData.value = { tables: [] }
  activeTable.value = ''
}

const selectTemplate = (template) => {
  selectedTemplate.value = template
  
  // 设置默认值
  if (template.fields) {
    template.fields.forEach(field => {
      if (field.default !== undefined) {
        formData.value[field.name] = field.default
      }
    })
  }
}

const getIcon = (iconName) => {
  const icons = {
    'Document': Document,
    'Grid': Grid,
    'Connection': Connection
  }
  return icons[iconName] || Document
}

const handleFileChange = (file) => {
  formData.value.file = file.raw
  console.log('文件选择:', file.name)
}

const nextStep = async () => {
  if (step.value === 1) {
    step.value = 2
  } else if (step.value === 2) {
    // 验证表单
    if (!formRef.value) return
    
    try {
      await formRef.value.validate()
      
      // 模拟数据连接和预览
      loading.value = true
      await simulateDataConnection()
      step.value = 3
      
      if (previewData.value.tables?.length > 0) {
        activeTable.value = previewData.value.tables[0].name
      }
    } catch (error) {
      console.error('表单验证失败:', error)
    } finally {
      loading.value = false
    }
  }
}

const prevStep = () => {
  if (step.value > 1) {
    step.value--
  }
}

const simulateDataConnection = async () => {
  // 模拟数据连接过程
  await new Promise(resolve => setTimeout(resolve, 1000))
  
  // 根据数据源类型生成示例数据
  if (selectedTemplate.value?.type === 'excel' || selectedTemplate.value?.type === 'csv') {
    previewData.value = {
      tables: [
        {
          name: 'Sheet1',
          columns: [
            { name: 'ID', type: 'number' },
            { name: '姓名', type: 'text' },
            { name: '年龄', type: 'number' },
            { name: '部门', type: 'text' },
            { name: '薪资', type: 'number' }
          ],
          rows: [
            { ID: 1, 姓名: '张三', 年龄: 25, 部门: '技术部', 薪资: 8000 },
            { ID: 2, 姓名: '李四', 年龄: 30, 部门: '销售部', 薪资: 6500 },
            { ID: 3, 姓名: '王五', 年龄: 28, 部门: '技术部', 薪资: 9500 }
          ]
        }
      ]
    }
  } else if (selectedTemplate.value?.type === 'database') {
    previewData.value = {
      tables: [
        {
          name: 'users',
          columns: [
            { name: 'id', type: 'number' },
            { name: 'username', type: 'text' },
            { name: 'email', type: 'text' },
            { name: 'created_at', type: 'date' }
          ],
          rows: [
            { id: 1, username: 'admin', email: 'admin@example.com', created_at: '2024-01-01' },
            { id: 2, username: 'user1', email: 'user1@example.com', created_at: '2024-01-02' }
          ]
        },
        {
          name: 'orders',
          columns: [
            { name: 'id', type: 'number' },
            { name: 'user_id', type: 'number' },
            { name: 'amount', type: 'number' },
            { name: 'status', type: 'text' }
          ],
          rows: [
            { id: 1, user_id: 1, amount: 100.00, status: 'completed' },
            { id: 2, user_id: 2, amount: 250.50, status: 'pending' }
          ]
        }
      ]
    }
  } else if (selectedTemplate.value?.type === 'api') {
    previewData.value = {
      tables: [
        {
          name: 'api_data',
          columns: [
            { name: 'id', type: 'number' },
            { name: 'title', type: 'text' },
            { name: 'value', type: 'number' },
            { name: 'timestamp', type: 'date' }
          ],
          rows: [
            { id: 1, title: '数据1', value: 100, timestamp: '2024-01-01T10:00:00Z' },
            { id: 2, title: '数据2', value: 200, timestamp: '2024-01-01T11:00:00Z' }
          ]
        }
      ]
    }
  }
}

const confirmAdd = async () => {
  loading.value = true
  
  try {
    // 构建数据源对象
    const dataSource = {
      name: formData.value.name,
      description: formData.value.description,
      type: selectedTemplate.value.type,
      config: { ...formData.value },
      tables: previewData.value.tables.map(table => ({
        name: table.name,
        description: `${table.name}表`,
        rowCount: table.rows?.length || 0,
        fields: table.columns.map(column => ({
          name: column.name,
          dataType: column.type === 'number' ? 'number' : 
                   column.type === 'date' ? 'date' : 'text',
          category: column.type === 'number' ? '度量值' : '维度',
          isPrimaryKey: column.name.toLowerCase() === 'id',
          isForeignKey: column.name.toLowerCase().includes('_id') && column.name.toLowerCase() !== 'id',
          isCalculated: false
        }))
      }))
    }
    
    // 添加到store
    const newDataSource = dataModelStore.addDataSource(dataSource)
    
    ElMessage.success('数据源添加成功')
    emit('data-source-added', newDataSource)
    handleClose()
  } catch (error) {
    console.error('添加数据源失败:', error)
    ElMessage.error('添加数据源失败')
  } finally {
    loading.value = false
  }
}

const handleClose = () => {
  visible.value = false
}
</script>

<style scoped>
.data-source-dialog {
  min-height: 400px;
}

.step-content h4 {
  margin: 0 0 20px 0;
  color: #303133;
  font-size: 16px;
}

.source-types {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 16px;
}

.source-type-card {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 16px;
  border: 2px solid #e4e7ed;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.2s ease;
}

.source-type-card:hover {
  border-color: #409EFF;
  background: #ecf5ff;
}

.source-type-card.selected {
  border-color: #409EFF;
  background: #ecf5ff;
}

.card-icon {
  color: #409EFF;
}

.card-content h5 {
  margin: 0 0 4px 0;
  color: #303133;
  font-size: 14px;
}

.card-content p {
  margin: 0;
  color: #909399;
  font-size: 12px;
}

.preview-section {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.preview-info {
  margin-bottom: 16px;
}

.table-preview {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.preview-tip {
  text-align: center;
  padding: 8px;
  background: #f8f9fa;
  border-radius: 4px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

:deep(.el-upload-dragger) {
  width: 100%;
}
</style>
